//
//  ViewController.m
//  图片破碎效果
//
//  Created by lanouhn on 16/7/19.
//  Copyright © 2016年 shenyanlong. All rights reserved.
//

#import "ViewController.h"

#define Width 8

@interface ViewController ()
/* 创建一个UIView属性 */
@property (nonatomic, strong) UIView *containerView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /* 调用创建视图方法 */
    [self createUI];
    /* 调用破碎设置方法 */
    [self crumbling];
    /* 设置破碎方法 */
    [self performSelector:@selector(animation) withObject:nil afterDelay:1.0];
}

#pragma mark -- 创建UI视图
- (void)createUI
{
    self.view.layer.contents = (__bridge id)[UIImage imageNamed:@"07"].CGImage;
    self.containerView = [[UIView alloc] initWithFrame:self.view.bounds];
}

#pragma mark -- 创建破碎
- (void)crumbling
{
    //屏幕快照,view中存着当前拍照的一刻的图像,参数BOOL为YES 立即生成快照, 还是在需要更新时再生成
    UIView *view = [self.view snapshotViewAfterScreenUpdates:YES];
    //分别获取屏幕当前的宽度和高度都可以放下的粒子,并给定frame
    for (int i = 0; i < CGRectGetMaxY(self.view.frame) / Width; i++)
    {
        for (int j = 0; j < CGRectGetMaxX(self.view.frame) / Width; j++)
        {
            CGRect snapshotRegion = CGRectMake(j * Width, i * Width, Width, Width);
            //复制一个指定范围偏移的复合视图
            UIView *snapshot = [view resizableSnapshotViewFromRect:snapshotRegion afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];
            snapshot.frame = snapshotRegion;
            [self.containerView addSubview:snapshot];
        }
    }
    [self.view addSubview:self.containerView];
}

#pragma mark -- 设置动画
- (void)animation
{
    [UIView animateWithDuration:3.0 animations:^{
       
        for (UIView *view in self.containerView.subviews)
        {
            view.center = CGPointMake(arc4random() % 1125 - 375, CGRectGetMaxY(self.view.frame) + 20);
        }
        
    }];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
